﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using UniRlv.COL;
using UniRlv.Utility;
using System.Threading;
using UniRlv.UI.Main.Widget;//引用此命名
using UniRlv.Utility.Extend;
using System.Linq;
using System.IO;

namespace UniRlv.UI.Main.ManufactureManage
{
    public partial class FrmTaskRun : UniRlv.UI.Main.FrmBase
    {
        BindingList<ProductionTask> details = new BindingList<ProductionTask>();
        FrmProcessBar progBar = null;
        int checkQty = 50;
        public FrmTaskRun()
        {
            InitializeComponent();
        }

        private void FrmTaskAddOrEdit_Load(object sender, EventArgs e)
        {
            #region 初始化工具栏

            toolBtnModify.Visible = true;
            toolBtnAdd.Visible = true;
            toolBtnDelete.Visible = true;
            toolBtnOpen.Visible = true;

            toolBtnAdd.Click += toolBtnAdd_Click;
            toolBtnDelete.Click += toolBtnDelete_Click;
            toolBtnModify.Click += toolBtnModify_Click;
            toolBtnOpen.Click += toolBtnOpen_Click;

            ToolStripButton btnRunTask = AddToolButton("RunTask", "启动任务");
            btnRunTask.Click += btnRunTask_Click;

            #endregion

            #region 初始化DataGridView和数据源

            UIHelper.InitDataGridView(dgvDetails);

            dgvDetails.DataSource = details;

            #endregion

            #region 初始化任务信息
            Wait();

            string msg = string.Empty;
            string sql = EntityHelper.GetQuerySql<ProductionTask>();
            List<ProductionTask> li = DALOpr.Query<ProductionTask>("state<" + (int)task_state.TS_VERIFIED, ref msg);
            if (li!=null && li.Count>0)
            {
                foreach (var item in li)
                {
                    details.Add(item);
                }
            }

            WaitBack();

            #endregion

            checkQty = ConfigurationHelper.AppGetInt("checkDataQty");
        }



        #region 工具栏响应
        private void btnRunTask_Click(object sender, EventArgs e)
        {
            if (WorkSpace.GetInstance().IfTaskFree())
            {
                if (dgvDetails.CurrentRow != null)
                {
                    ProductionTask p = dgvDetails.CurrentRow.DataBoundItem as ProductionTask;
                    string msg = string.Empty;

                    List<PrintInfo> li = DALOpr.Query<PrintInfo>("taskID = " + p.ID, ref msg);

                    if (MessageBox.Show(this, "确定需要启动该任务：" + p.ToString(), "请确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK)
                    {
                        int nSel = ConfigurationHelper.AppGetInt("dupCheckType");
                        if (nSel == 1)
                        {
                            if (!File.Exists(p.extendInfo))
                            {
                                MessageBox.Show("查重数据源文件不存在，请重新指定！");
                                return;
                            }
                        }

                        PublicObject.CurTask = p;
                        PublicObject.CurPrintInfos = li;

                        msg = string.Empty;
                        PublicObject.CurLine = DALOpr.QuerySingle<ProductionLine>("select * from ProductionLine where id=" + p.lineID, ref msg);
                        this.backgroundWorker1.RunWorkerAsync(nSel); // 运行 backgroundWorker 组件

                        progBar = new FrmProcessBar(this.backgroundWorker1);// 显示进度条窗体
                        progBar.Text = "加载任务信息";
                        progBar.Show(this);
                    }
                }
                else
                {
                    ShowInfoMessageBox("提示", "先选择需要启动的任务");
                }
            }
            else
            {
                ShowInfoMessageBox("提示", "当前生产中，不允许再次启动任务！");
            }

        }

        void toolBtnOpen_Click(object sender, EventArgs e)
        {

        }

        private void toolBtnModify_Click(object sender, EventArgs e)
        {
            if (dgvDetails.CurrentRow != null)
            {
                ProductionTask p = dgvDetails.CurrentRow.DataBoundItem as ProductionTask;
                string msg = string.Empty;

                List<PrintInfo> li = DALOpr.Query<PrintInfo>("taskID = " + p.ID, ref msg);

                FrmAddOrEditTask frm = new FrmAddOrEditTask();
                frm.Text = "修改任务信息";
                frm.Task = p;

                if (li!=null)
                {
                    foreach (var item in li)
                    {
                        frm.PrintInfos.Add(item);
                    }
                }

                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    p = frm.Task;
                    msg = string.Empty;
                    string sql = EntityHelper.GetUpdateSql(p);

                    sql += "|";
                    sql += "delete from PrintInfo where taskID=" + p.ID;
 
                    if (frm.PrintInfos != null && frm.PrintInfos.Count > 0)
                    {
                        sql += "|";
                        sql += EntityHelper.GetInsertSqls(frm.PrintInfos);
                    }

                    if (DALOpr.ExecuteNonQueryTran(sql, ref msg))
                    {
                        int idx = details.IndexOf(p);
                        details.RemoveAt(idx);
                        details.Insert(idx, p);

                        dgvDetails.SetRowSelect(details.Count - 1);
                        ShowInfoMessageBox("提示", "修改成功");
                    }
                    else
                    {
                        ShowErrorMessageBox("修改失败", msg);
                    }
                }
            }
            else
            {
                ShowInfoMessageBox("提示", "先选择需要修改的记录");
            }
        }

        private void toolBtnDelete_Click(object sender, EventArgs e)
        {
            if (dgvDetails.CurrentRow != null)
            {
                ProductionTask p = dgvDetails.CurrentRow.DataBoundItem as ProductionTask;

                if (ShowConfirmDialog("请确认", "确定要删除该记录？\r\n" + p.ToString()) == System.Windows.Forms.DialogResult.OK)
                {
                    string sql = "delete from ProductionTask where id = " + p.ID;
                    string msg = string.Empty;

                    if (DALOpr.ExecuteNonQuery(sql, ref msg))
                    {
                        details.Remove(p);
                    }
                    else
                    {
                        ShowErrorMessageBox("删除失败", msg);
                    }
                }
            }
            else
            {
                ShowInfoMessageBox("提示", "先选择需要删除的记录");
            }
        }

        private void toolBtnAdd_Click(object sender, EventArgs e)
        {
            FrmAddOrEditTask frm = new FrmAddOrEditTask();
            frm.Text = "添加任务信息";
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ProductionTask p = frm.Task;
                string msg = string.Empty;
                string sql = EntityHelper.GetInsertSql(p);

                if (frm.PrintInfos!=null && frm.PrintInfos.Count>0)
                {
                    sql += "|";
                    sql += EntityHelper.GetInsertSqls(frm.PrintInfos);

                    if (DALOpr.ExecuteNonQueryTran(sql, ref msg))
                    {
                        details.Add(p);

                        dgvDetails.SetRowSelect(details.Count - 1);
                        ShowInfoMessageBox("提示", "添加成功");
                    }
                    else
                    {
                        ShowErrorMessageBox("添加失败", msg);
                    }
                }
                else
                {
                    if (DALOpr.Insert(p, ref msg))
                    {
                        details.Add(p);

                        dgvDetails.SetRowSelect(details.Count - 1);
                        ShowInfoMessageBox("提示", "添加成功");
                    }
                    else
                    {
                        ShowErrorMessageBox("添加失败", msg);
                    }
                }

            }
        }

        #endregion


        private void dgvDetails_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvDetails.CurrentRow != null)
            {
                toolBtnModify.PerformClick();
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            string msg = string.Empty;

            int nType = Convert.ToInt32(e.Argument);
            List<CodeInfo> li = new List<CodeInfo>();

            if (nType == 0)
            {

                //加载历史扫描数据
                worker.ReportProgress(0, "加载历史数据...\r\n");
                int cnt = Convert.ToInt32(DALOpr.RawGetScalar("SELECT count(a.id) FROM [CodeInfo] a join ProductionTask b on a.taskID=b.id where b.productID = " + PublicObject.CurTask.productID, ref msg));
               
                int pages = cnt == 0 ? 0 : (cnt - 1) / 10000 + 1;

                if (pages > 0)
                {
                    //最多加载checkQty万
                    for (int i = 1; i <= pages && i <= checkQty; i++)
                    {
                        li.AddRange(DALOpr.QueryCodeHistoryPageByProduct(i, 10000, PublicObject.CurTask.productID, ref msg));
                        worker.ReportProgress(i * 94 / pages, ".");
                    }
                }
                else
                {
                    worker.ReportProgress(93, "加载历史数据完成.\r\n");
                }

                PublicObject.CodeScanned.AddRange(li.ConvertAll<string>(s => s.code));
            }
            else if(nType == 1)
            {
                worker.ReportProgress(0, "加载查重数据源...\r\n");
                string[] lines = File.ReadAllLines(PublicObject.CurTask.extendInfo, Encoding.UTF8);

                string code24BIt="";
                foreach (var item in lines)
                {
                    if (AppHelper.SYZSGet24BitFromCode(ref code24BIt, item, 2))
                    {
                        PublicObject.CodeValid.Add(item);
                    }
                }

                if (PublicObject.CodeValid.Count == 0)
                {
                    string err = "无合法的数据可查重";
                    //worker.ReportProgress(100, "加载失败：" + err);
                    e.Result = "加载失败：" + err;
                    return;
                }
            }
            else
            {//不查重
                CodePrcUtility.DUP_CHECK = false;
            }
            //for (int i = 0; i <= 100; i++)
            //{
            //    Thread.Sleep(100);
            //    worker.ReportProgress(i, i.ToString() + "  你好！\r\n"); //注意：这里向子窗体返回信息值，这里是两个值，一个用于进度条，一个用于文本框的。
            //    if (worker.CancellationPending)  // 如果用户取消则跳出处理数据代码 
            //    {
            //        e.Cancel = true;
            //        break;
            //    }
            //}


            //加载关联数据 
            FrmMain.GetInstance().lastRltCodeLoadTime = DateTime.Now;

            string whereString = $" batch={PublicObject.CurTask.batch} and inTime<='{FrmMain.GetInstance().lastRltCodeLoadTime.ToString("yyyy-MM-dd HH:mm:ss")}' and pzwh='{PublicObject.CurTask.pzwh}'";
            worker.ReportProgress(94, "加载关联码....\r\n");

            List<CodeRltInfo> rss = DALOpr.Query<CodeRltInfo>(whereString, ref msg);

            if (rss != null && rss.Count > 0)
            {
                PublicObject.CodeRlt.AddRange(rss);
            }

            //加载数据
            worker.ReportProgress(95, "加载一级码....\r\n");
            whereString = string.Format(" taskID='{0}' and stationNumber=1 and (codeState=1 or codeState=2) order by serialNumber", PublicObject.CurTask.ID);
            li = DALOpr.Query<CodeInfo>(whereString, ref msg);
            PublicObject.arrCode1.GetList(1).AddRange(li.FindAll((t) => { return t.subDeviceNumber != 0; }));
            PublicObject.arrCode1.GetList(0).AddRange(li.FindAll((t) => { return t.subDeviceNumber == 0; }));
            //PublicObject.arrCode1.GetList(0).AddRange(li.FindAll((t) => { return t.taskID == PublicObject.CurTask.ID && t.stationNumber == 1 && t.subDeviceNumber == 0; }).OrderBy(c => c.serialNumber));
            //PublicObject.arrCode1.GetList(1).AddRange(li.FindAll((t) => { return t.taskID == PublicObject.CurTask.ID && t.stationNumber == 1 && t.subDeviceNumber != 0; }).OrderBy(c => c.serialNumber));

            worker.ReportProgress(96, "加载一级码完成，加载二级码....\r\n");

            whereString = string.Format(" taskID='{0}' and stationNumber=2 and (codeState=1 or codeState=2) order by serialNumber", PublicObject.CurTask.ID);
            PublicObject.arrCode2 = DALOpr.Query<CodeInfo>(whereString, ref msg);
            //PublicObject.arrCode2.AddRange(li.FindAll((t) => { return t.taskID == PublicObject.CurTask.ID && t.stationNumber == 2 && t.subDeviceNumber == 0; }).OrderBy(c => c.serialNumber));
            worker.ReportProgress(97, "加载二级码完成，加载三级码....\r\n");

            whereString = string.Format(" taskID='{0}' and stationNumber=3 and (codeState=1 or codeState=2) order by serialNumber", PublicObject.CurTask.ID);
            PublicObject.arrCode3 = DALOpr.Query<CodeInfo>(whereString, ref msg);
            //PublicObject.arrCode3.AddRange(li.FindAll((t) => { return t.taskID == PublicObject.CurTask.ID && t.stationNumber == 3 && t.subDeviceNumber == 0; }).OrderBy(c => c.serialNumber));
            worker.ReportProgress(98, "加载三级码完成，加载四级码....\r\n");

            whereString = string.Format(" taskID='{0}' and stationNumber=4 and (codeState=1 or codeState=2) order by serialNumber", PublicObject.CurTask.ID);
            PublicObject.arrCode4 = DALOpr.Query<CodeInfo>(whereString, ref msg);
            //PublicObject.arrCode4.AddRange(li.FindAll((t) => { return t.taskID == PublicObject.CurTask.ID && t.stationNumber == 4 && t.subDeviceNumber == 0; }).OrderBy(c => c.serialNumber));
            worker.ReportProgress(99, "加载四级码完成，启动任务....\r\n");

            if (WorkSpace.GetInstance().RunTask())
            {
                e.Result = null;
                //worker.ReportProgress(100, "加载完成！");
            }
            else
            {
                string err = WorkSpace.GetInstance().ErrorString;
                //worker.ReportProgress(100, "加载失败：" + err);
                e.Result = "加载失败：" + err;
            }
            
            
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            progBar.Close();

            if (e.Result != null)
            {
                PublicObject.CurTask = null;
                //清空已加载数据
                PublicObject.arrCode1.Clear();
                PublicObject.arrCode2.Clear();
                PublicObject.arrCode3.Clear();
                PublicObject.arrCode4.Clear();
                PublicObject.CodeScanned.Clear();

                MessageBox.Show(e.Result.ToString());
            }
            else if (e.Cancelled)
            {
                MessageBox.Show("操作取消");
            }
            else
            {
                FrmMain.GetInstance().SwitchFormByModuleName("WarehourseInStatus");
            }
        }
    }
}
